
//
//  MenuAdjustViewController.m
//  whereToEatMerchat
//
//  Created by WTFSSD on 2017/7/3.
//  Copyright © 2017年 WTFSSD. All rights reserved.
//

#import "BaseContentScrollViewController.h"



@interface BaseContentScrollViewController ()<UIScrollViewDelegate>


///容器
@property(nonatomic,strong)UIScrollView * contentScrollView;

///顶部
@property(nonatomic,strong)UIView * titleView;



///滑动
@property(nonatomic,strong)UIView * indicator;



///当前 标题按钮
@property(nonatomic,strong)UIButton * currentButton;

@property(nonatomic,assign)CGRect indicatorCurrntRect;


@property(nonatomic,strong)NSArray * controllersArray;


@property(nonnull,strong)UIButton * lastButton;


@end

@implementation BaseContentScrollViewController


+(instancetype)controllerWith:(NSDictionary *)config{
    return [super controllerWith:config];
}

- (void)viewDidLoad {
    [super viewDidLoad];
   // self.currentIndex = 0;
}

-(instancetype)initWithCoder:(NSCoder *)coder{
    self = [super initWithCoder:coder];
    if (self) {

         [self initWithViewControllers];

    }
    return self;


}

- (void)setConfig:(NSDictionary *)config{
    [super setConfig:config];
    self.controllersArray = config[kControllers]?config[kControllers]:@[];
    [self initWithViewControllers];
}


-(void)setControllerClassNames:(NSString *)controllerClassNames{
    self.controllersArray = [controllerClassNames componentsSeparatedByString:@","];
    [self initWithViewControllers];
    
}

-(void)setTitles:(NSArray<NSString *> *)titles{
    for (int i = 0 ; i < self.childViewControllers.count; i++) {
        UIViewController * vc = self.childViewControllers[i];
        vc.title = titles[i];

        UIButton * btn = (UIButton*)self.titleView.subviews[i];
        
         btn.titleLabel.font = [UIFont fontWithName:default_fontname size:autoScaleW(14)];
        [btn setTitleColor:RGBA(102, 102, 102, 1) forState:UIControlStateNormal];

        [btn setTitle:titles[i] forState:UIControlStateNormal];
        [btn setTitle:titles[i] forState:UIControlStateSelected];
    }
}

-(void)setTitle:(NSString *)title forIndex:(NSInteger)index{
    if (index < 0 || index > self.childViewControllers.count) {
        return;
    }else{
        UIViewController * vc = self.childViewControllers[index];
        vc.title = title;
        //
        UIButton * btn = (UIButton*)self.titleView.subviews[index];

        btn.titleLabel.font = [UIFont fontWithName:default_fontname size:autoScaleW(14)];

        [btn setTitleColor:RGBA(102, 102, 102, 1) forState:UIControlStateNormal];

        [btn setTitle:title forState:UIControlStateNormal];
        [btn setTitle:title forState:UIControlStateSelected];
    }
}

-(void)initWithViewControllers{

    WeakSelf(weakSelf);

    if (self.childViewControllers.count > 0) {
        return;
    }
    NSArray * controllers = self.controllersArray;
    
    if (!self.controllersArray.count||self.controllersArray.count <= 0) {

        return;
    }
    
    UIView * titleView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:titleView];
    
    [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left);
        CGFloat offset = 0.f;
        if (self.navigationController.navigationBar.translucent) {
            offset = 64.f;
        }
        make.top.equalTo(weakSelf.view.mas_top).offset(offset);
        make.right.equalTo(weakSelf.view.mas_right);
        make.height.mas_equalTo(44);
    }];

    //滚动视图  底部视图
    UIScrollView * contentScrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:contentScrollView];
    contentScrollView.pagingEnabled = YES;
    contentScrollView.delegate = self;
    contentScrollView.showsVerticalScrollIndicator = NO;
    contentScrollView.showsHorizontalScrollIndicator = NO;
    contentScrollView.backgroundColor = HexColor(0xcccccc);
    contentScrollView.contentSize = CGSizeMake(self.view.frame.size.width*controllers.count, 0);
    contentScrollView.backgroundColor = HexColor(0xcccccc);
    [contentScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left);
        make.top.equalTo(titleView.mas_bottom);
        make.right.equalTo(weakSelf.view.mas_right);
        make.bottom.equalTo(weakSelf.view.mas_bottom);
    }];

    UIButton * lastBtn = nil;
    NSInteger cindex = 0;

    NSLog(@"count %ld",controllers.count);

    for (id   obj in controllers) {
        UIViewController * vc = nil;
        if ([obj isKindOfClass:[UIViewController class]]) {
            vc = obj;
        }
        if ([obj isKindOfClass:[NSString class]]) {
            Class cls  = NSClassFromString(obj);
            vc = [[cls alloc] init];
        }
        NSString * btnText = vc.title ? vc.title:@"tab ".add(@(cindex));
        [self addChildViewController:vc];
        [contentScrollView addSubview:vc.view];

        [vc.view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(cindex*self.view.frame.size.width);
            make.width.equalTo(self.view.mas_width);
            make.top.equalTo(titleView.mas_bottom);
            make.height.equalTo(contentScrollView.mas_height);
        }];
        
        UIButton * btn = [[UIButton alloc] initWithFrame:CGRectZero];
        [btn setTitle:btnText forState:UIControlStateNormal];
        [btn setTitle:btnText forState:UIControlStateSelected];
        
        [btn setTitleColor:HexColor(0x333333) forState:UIControlStateNormal];
        [btn setTitleColor:RGB(63, 143, 243) forState:UIControlStateSelected];
        
        
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [titleView addSubview:btn];
        
        if (lastBtn) {
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(lastBtn.mas_right);
                make.top.equalTo(lastBtn.mas_top);
                make.height.equalTo(lastBtn.mas_height);
                make.width.equalTo(lastBtn.mas_width);
            }];
        }else{
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(titleView.mas_left);
                make.top.equalTo(titleView.mas_top);
                make.height.equalTo(titleView.mas_height).offset(-1);
                make.width.equalTo(titleView.mas_width).dividedBy(controllers.count);
            }];
            btn.selected = YES;
            self.currentButton = btn;
        }
        
        lastBtn = btn;
        cindex++;
    }


   //  竖线

    for (int i = 0 ; i < controllers.count - 1 ; i++) {

       UIView  *_lineView = [[UIView alloc]init];

        _lineView.backgroundColor = [UIColor lightGrayColor];

        [titleView addSubview:_lineView];

        [_lineView mas_makeConstraints:^(MASConstraintMaker *make) {

            make.centerY.mas_equalTo(titleView);
            make.left.mas_equalTo(weakSelf.view.frame.size.width/controllers.count * (i + 1));

            make.height.equalTo(titleView.mas_height).dividedBy(2);
            make.width.mas_equalTo(1);
        }];


    }

    //  滚动下滑环线
    UIView * indicator = [[UIView alloc] initWithFrame:CGRectZero];
    indicator.backgroundColor = RGB(63, 143, 243);
    [titleView addSubview:indicator];
    [indicator mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.currentButton.mas_centerX);
        make.height.mas_equalTo(2);
        make.width.equalTo(self.currentButton.mas_width).multipliedBy(0.6);
        make.bottom.equalTo(titleView.mas_bottom).offset(-1);
    }];

     // 底部阴影线

    UIView * bottomLineView = [[UIView alloc] initWithFrame:CGRectZero];
    bottomLineView.backgroundColor = RGB(216, 216, 216);
    [titleView addSubview:bottomLineView];
    [bottomLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view);
        make.height.mas_equalTo(1);
        make.width.equalTo(weakSelf.view);
        make.bottom.equalTo(titleView.mas_bottom).offset(0);
    }];

    
    self.contentScrollView = contentScrollView;
    self.titleView = titleView;
    self.indicator = indicator;
    self.indicatorCurrntRect = self.indicator.frame;


}

-(void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    if (self.childViewControllers.count<=0) {
        return;
    }
    WeakSelf(weakSelf);
    CGFloat offset = 0;
    if (self.navigationController.navigationBar.translucent) {
        offset = 64.f;
    }
    if (self.preferredInterfaceOrientationForPresentation != UIInterfaceOrientationPortrait) {
        offset -=20;
    }
    [self.titleView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_top).offset(self.navigationController.navigationBar.hidden?20:offset);
    }];
    self.contentScrollView.contentSize = CGSizeMake(self.view.frame.size.width*self.childViewControllers.count, 0);
    for (int i = 0 ; i<self.childViewControllers.count; i++) {
        UIViewController * vc = self.childViewControllers[i];
        [vc.view mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(i*self.view.frame.size.width);
            make.width.equalTo(self.view.mas_width);
            make.top.equalTo(self.titleView.mas_bottom);
            make.height.equalTo(self.contentScrollView.mas_height);
        }];
    }
}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.indicatorCurrntRect = self.indicator.frame;
    [self.contentScrollView setContentOffset:CGPointMake(self.currentIndex*self.view.frame.size.width, self.contentScrollView.contentOffset.y) animated:YES];
}


-(void)btnClick:(UIButton * )sender{
    
    NSInteger currentIndex = ceil((sender.frame.origin.x/self.titleView.frame.size.width)*self.contentScrollView.contentSize.width/self.view.frame.size.width);
    self.currentIndex = currentIndex;
    NSLog(@"%ld",currentIndex);

    if (!self.currentButton){
        [sender setSelected:YES];
        self.currentButton = sender;
    }else if (self.currentButton != sender){
        self.currentButton.selected = NO;
        [self.currentButton setSelected:NO];
        self.indicatorCurrntRect = self.indicator.frame;
        self.currentButton = sender ;
        [self.currentButton setSelected:YES];
        
        [self.contentScrollView setContentOffset:CGPointMake(self.view.frame.size.width*currentIndex, self.contentScrollView.contentOffset.y) animated:YES];
    }else{
        return;
    }
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self endScroll:scrollView];
}

-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    [self endScroll:scrollView];
}


-(void)endScroll:(UIScrollView*)scrollView{
    self.currentIndex = scrollView.contentOffset.x/self.view.frame.size.width;
    if (self.currentButton == self.titleView.subviews[self.currentIndex]) {
        
    }else{
        self.currentButton.selected = NO;
        self.currentButton =self.titleView.subviews[self.currentIndex];
        self.currentButton.selected = YES;
    }
    
    self.indicatorCurrntRect = self.indicator.frame;
    
    [self.indicator mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.currentButton.mas_centerX);
        make.bottom.equalTo(self.titleView.mas_bottom).offset(-1);
        make.width.equalTo(self.currentButton.mas_width).multipliedBy(0.6);
        make.height.mas_equalTo(2);
    }];
    [self.indicator.superview layoutIfNeeded];
    
    if (self.contentDelegate && [self.contentDelegate respondsToSelector:@selector(BaseContentScrollViewController:didCnangeChildViewController:)]) {
        [self.contentDelegate BaseContentScrollViewController:self didCnangeChildViewController:self.childViewControllers[self.currentIndex]];
    }
}



-(void)setUpNavBar{
    [super setUpNavBar];
    self.title = self.config[kTitle];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

-(void)setCurrentViewControllerIndex:(NSInteger)index{
    self.currentIndex = index;
    [self.contentScrollView setContentOffset:CGPointMake(self.view.frame.size.width*self.currentIndex, self.contentScrollView.contentOffset.y) animated:YES];
}

@end

const NSString * kControllers = @"__Controllers";
